//
//  MNDWithdrawViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/11.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDWithdrawViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MNDBankModel.h"
#import "MNDBankCardViewController.h"
#import "MNDBindBankcardViewController.h"
#import "MNDWithdrawParamModel.h"
#import "MNDWebViewController.h"
#import "MNDTransactionRecordViewController.h"
#import "MNDWithdrawAlertViewController.h"
#import "MNDOpenDeposAlertViewController.h"
#import "MNDDepositAlertViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDOpenTermsAuthViewController.h"

@interface MNDWithdrawViewController ()

//银行logo
@property (weak, nonatomic) IBOutlet UIImageView *bankLogoImageView;
//银行名称
@property (weak, nonatomic) IBOutlet UILabel *bankLabel;
//银行卡尾号
@property (weak, nonatomic) IBOutlet UILabel *bankcardLabel;
//余额
@property (weak, nonatomic) IBOutlet UILabel *userBalanceLabel;
//全部提现Button
@property (weak, nonatomic) IBOutlet UIButton *allWithdrawBtn;
//提现金额输入框
@property (weak, nonatomic) IBOutlet UITextField *withdrawTextField;
//应付金额
@property (weak, nonatomic) IBOutlet UILabel *arrivalAmountLabel;
//手续费
@property (weak, nonatomic) IBOutlet UILabel *handlingChargeLabel;
//手续费说明
@property (weak, nonatomic) IBOutlet UILabel *handlingChargeDetailLabel;

//绑卡按钮
@property (weak, nonatomic) IBOutlet UIButton *bindCardBtn;
//显示银行卡信息
@property (weak, nonatomic) IBOutlet UIButton *cardDetailBtn;

@property (strong, nonatomic) MNDBankModel *bankModel;

@property (strong, nonatomic) MNDWithdrawParamModel *withdrawParam;
@property (weak, nonatomic) MNDWithdrawAlertViewController *alertVC;

@end

@implementation MNDWithdrawViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.cardDetailBtn setEnabled:NO];
    [self.bindCardBtn setEnabled:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(withdrawResult:) name:@"withdraw_result" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(withdrawResultRecord:) name:@"withdraw_record" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backToRootVC:) name:@"withdraw_back" object:nil];
    
    [self initialBarButtonItems];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadBankInfo];
    [self loadWithdrawParam];
    [self initialContents];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initialContents {
    self.withdrawTextField.text = @"";
    self.withdrawTextField.font = [UIFont systemFontOfSize:14.0];
    self.handlingChargeLabel.text = @"手续费：￥0.00";
    self.arrivalAmountLabel.text = @"应付金额：￥0.00";
}

- (void)initialBarButtonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    UIImage *itemImage = [UIImage imageNamed:@"notice_help_icon"];
    UIBarButtonItem *helpItem = [[UIBarButtonItem alloc] initWithImage: itemImage
                                                                 style: UIBarButtonItemStylePlain
                                                                target: self
                                                                action: @selector(helpBtnAction:)];
    helpItem.tintColor = kColorOrange;
    
    self.leftBarTintColor = kColorOrange;
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = helpItem;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, helpItem];
    }
}

- (void)helpBtnAction :(id)sender {
    
    if (self.alertVC) {
        return;
    }
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Withdraw" bundle:nil];
    MNDWithdrawAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:[MNDWithdrawAlertViewController description]];
    [self.view addSubview:alertVC.view];
    [self addChildViewController:alertVC];
    
    self.alertVC = alertVC;
    
}

- (void)backToRootVC :(NSNotification *)notification {
    [self.navigationController popToRootViewControllerAnimated:YES];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"reload_user_infos" object:nil];
}

- (void)withdrawResult:(NSNotification *)notification {
//    [NetworkProgressHUD showHudMsg:@"提现成功"];
    [self initialContents];
//    [self.navigationController popViewControllerAnimated:YES];
}

- (void)withdrawResultRecord:(NSNotification *)notification {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Transaction" bundle:nil];
    
    MNDTransactionRecordViewController *recordVC = [storyboard instantiateViewControllerWithIdentifier:[MNDTransactionRecordViewController description]];
//    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:recordVC animated:YES];
//    self.hidesBottomBarWhenPushed = NO;
}

//全部提现
- (IBAction)withdrawAllMoneyAction:(id)sender {

    //可用余额为0不做处理
    if (self.withdrawParam.amountAvailable.doubleValue <= 0) {
        
        return;
    }
    self.withdrawTextField.font = [UIFont systemFontOfSize:25.0];
    self.arrivalAmountLabel.textColor = kColorBlack;
    [self.handlingChargeLabel setHidden:NO];
    [self.handlingChargeDetailLabel setHidden:NO];
    
    NSNumber *amountAvalible = [NSNumber numberWithString:self.withdrawParam.amountAvailable];
    NSNumber *canFree = [NSNumber numberWithString:self.withdrawParam.canFreeMoney];
    if (amountAvalible.doubleValue <= canFree.doubleValue) {
        self.arrivalAmountLabel.text = [NSString stringWithFormat:@"应付金额：￥%.02lf", amountAvalible.doubleValue];
        self.handlingChargeLabel.text = [NSString stringWithFormat:@"手续费：￥0.00"];
        self.withdrawTextField.text = [NSString stringWithFormat:@"%.02lf", amountAvalible.doubleValue];
    } else {
        
        NSDecimalNumber *amountNum = [NSDecimalNumber decimalNumberWithString:self.withdrawParam.amountAvailable];
        NSDecimalNumber *canFreeNum = [NSDecimalNumber decimalNumberWithString:self.withdrawParam.canFreeMoney];
        NSDecimalNumber *counterNum = [NSDecimalNumber decimalNumberWithString:self.withdrawParam.counterFee];
        //保留2位小数
        NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
        //特殊处理保留3位小数
        NSDecimalNumberHandler *handler3 = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers scale:3 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
        //收取手续费部分的金额
        NSDecimalNumber *feeMoneyNum = [amountNum decimalNumberBySubtracting:canFreeNum withBehavior:handler];
        //费率+1
        NSDecimalNumber *oneNum = [NSDecimalNumber decimalNumberWithString:@"1"];
        NSDecimalNumber *rateNum = [counterNum decimalNumberByAdding:oneNum withBehavior:handler3];
        NSLog(@"feenum:%@", feeMoneyNum);
        NSLog(@"rate---%@", rateNum);
//        NSDecimalNumber *feeNum = [feeMoneyNum decimalNumberByMultiplyingBy:counterNum withBehavior:handler];
        //收取手续费部分的金额除以（1+费率）等于提现金额
        NSDecimalNumber *withdrawMoney = [feeMoneyNum decimalNumberByDividingBy:rateNum withBehavior:handler];
        NSLog(@"withdraw: %@", withdrawMoney);
        //手续费==提现金额*费率
        NSDecimalNumber *feeNum = [withdrawMoney decimalNumberByMultiplyingBy:counterNum withBehavior:handler];
        NSLog(@"feenum: %@", feeNum);
        
//        double fee = (amountAvalible.doubleValue - canFree.doubleValue) * counterFee.doubleValue;
        //计算所得手续费低于最低手续费，则手续费为最低手续费
        NSNumber *lessMoney = [NSNumber numberWithString:self.withdrawParam.lessMoney];
        if ([feeNum doubleValue] < lessMoney.doubleValue) {
            self.handlingChargeLabel.text = [NSString stringWithFormat:@"手续费：￥%.02lf", lessMoney.doubleValue];
            
            NSDecimalNumber *lessNum = [NSDecimalNumber decimalNumberWithString:self.withdrawParam.lessMoney];
            self.withdrawTextField.text = [NSString stringWithFormat:@"%@", [amountNum decimalNumberBySubtracting:lessNum withBehavior:handler]];
            self.arrivalAmountLabel.text = [NSString stringWithFormat:@"应付金额：￥%@", amountNum];
        } else {
            self.handlingChargeLabel.text = [NSString stringWithFormat:@"手续费：￥%@", feeNum];
            self.withdrawTextField.text = [NSString stringWithFormat:@"%@", withdrawMoney];
            self.arrivalAmountLabel.text = [NSString stringWithFormat:@"应付金额：￥%@", [withdrawMoney decimalNumberByAdding:feeNum withBehavior:handler]];
        }
    }
}

//提现
- (IBAction)withdrawAction:(id)sender {
    
    NSString *withdrawMoney = self.withdrawTextField.text;
    if (withdrawMoney.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入提现金额"];
        return;
    }
    
    if (withdrawMoney.doubleValue <= 0) {
        [NetworkProgressHUD showHudMsg:@"提现金额应大于0"];
        return;
    }
    
    NSNumber *userAmount = [NSNumber numberWithString:self.bankModel.userAmount.userAmountAvailable];
    if (withdrawMoney.doubleValue > userAmount.doubleValue) {
        [NetworkProgressHUD showHudMsg:@"提现金额不能大于余额"];
        return;
    }
    
    if (self.bankModel.jxBankaccount.userAmountCardno.length <= 0) {
        [self bindCardAction:nil];
        return;
    }
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"withdraw_money": withdrawMoney,
                                                          @"withdraw_cnaps": self.bankModel.jxBankaccount.userAmountCardno,
                                                          @"withdraw_type" : @"1",
                                                          @"channel"       : @"app"}];
    
    [APIManager sendRequestWithPath:API_USER_WITHDRAW parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            [weakself loadUserEncode:responseModel.data];
        } else {
            NSDictionary *dict = responseModel.msg;
            if ([dict.allKeys containsObject:@"sign"]) {
                [NetworkProgressHUD hideHud];
                if ([responseModel.msg[@"sign"] isEqualToString:kOpenAccount] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSetPassword] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignPayment] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignAutoTender] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignAutoTransfer] ||
                    [responseModel.msg[@"sign"] isEqualToString:kRiskEvaluation] ||
                    [responseModel.msg[@"sign"] isEqualToString:kBandcard] ||
                    [responseModel.msg[@"sign"] isEqualToString:kExpiredSignPayment] ||
                    [responseModel.msg[@"sign"] isEqualToString:kExpiredAutotender]
                    ) {
                    [weakself showOpenDepositAlert:responseModel];
                }else {
                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                }
            } else {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)showOpenDepositAlert:(ResponseModel *)response {
    NSString *signStr = response.msg[@"sign"];
    if ([signStr isEqualToString:kOpenAccount]) {
        
        [self showOpenAccountAlertWithModel:response];
        return;
    }
    
    __weak MNDOpenDeposAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDeposAlertViewController description]];
    
    __weak UIView *alertView = alertVC.view;
    [KeyWindow addSubview:alertView];
    [self.tabBarController addChildViewController:alertVC];
    
    WeakSelf(self);
    
    [alertVC.confirmButton bk_addEventHandler:^(id sender) {
        [alertView removeFromSuperview];
        [alertVC removeFromParentViewController];
        
        [weakself toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    alertVC.alertMessage = response.msg[@"error"];
    alertVC.alertType = response.msg[@"sign"];
}

- (void)showOpenAccountAlertWithModel:(ResponseModel *)response {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDDepositAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:[MNDDepositAlertViewController description]];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self.tabBarController addChildViewController:alertVC];
    
    __weak typeof(self) weakSelf = self;
    
    [alertVC.depositBtn bk_addEventHandler:^(id sender) {
        [springView removeFromSuperview];
        [alertVC removeFromParentViewController];
        [weakSelf toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    [alertVC.closeBtn bk_addEventHandler:^(id sender) {
        
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainerView.frame = CGRectMake(alertVC.alertContainerView.frame.origin.x, kScreenHeight, alertVC.alertContainerView.frame.size.width, alertVC.alertContainerView.frame.size.height);
            alertVC.closeBtn.frame = CGRectMake(alertVC.closeBtn.frame.origin.x, kScreenHeight, alertVC.closeBtn.frame.size.width, alertVC.closeBtn.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)toOpenDepositoryWithModel:(ResponseModel *)response {
    
    NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
    
    NSString *signStr = response.msg[@"sign"];
    //开通存管
    if ([signStr isEqualToString:kOpenAccount]) {
        MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
        realVC.fromNaviIndex = index;
        
        [self.navigationController pushViewController:realVC animated:YES];
        
        return;
    }
    //设置交易密码
    if ([signStr isEqualToString:kSetPassword]) {
        
        [self loadPaymentPassword];
        return;
    }
    
    //设置缴费授权
    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment]) {
        
        MNDOpenTermsAuthViewController *openTermsAuthVC = [UIStoryboard viewControllerWithIdentifier:@"MNDOpenTermsAuthViewController"];
        openTermsAuthVC.fromNaviIndex = index;
        [self.navigationController pushViewController:openTermsAuthVC animated:YES];
        return;
//        MNDOpenDepositoryPaymentViewController *paymentVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryPaymentViewController description]];
//        paymentVC.fromNaviIndex = index;
//
//        [self.navigationController pushViewController:paymentVC animated:YES];
//
//        return;
    }
//    //设置自动投标
//    if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender]) {
//
//        MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
//        if (self.userPhone.length > 0) {
//            tenderVC.fromNaviIndex = index;
//            tenderVC.phoneNumber = self.userPhone;
//
//            [self.navigationController pushViewController:tenderVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
//    //设置自动债转
//    if ([signStr isEqualToString:kSignAutoTransfer]) {
//
//        MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
//        if (self.userPhone.length > 0) {
//            transferVC.fromNaviIndex = index;
//            transferVC.phoneNumber = self.userPhone;
//
//            [self.navigationController pushViewController:transferVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
}

/**
 设置交易密码
 */
- (void)loadPaymentPassword {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PASSWORD parameters:[MNDSign signedParamWithDict:@{@"channel": @"app"}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"设置交易密码";
            NSInteger index = [weakself.navigationController.viewControllers indexOfObject:weakself];
            webVC.fromNaviIndex = index;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadUserEncode: (NSString *)html {
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"user_code": user.user_code}];
    
    [APIManager sendRequestWithPath:API_ENCODE_USERCODE parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
                webVC.webViewUrl = html;
                webVC.naviBarHidden = NO;
                webVC.loadType = LoadTypeHTMLString;
                webVC.encodeUserCode = responseModel.data[@"user_code"];
                webVC.title = @"提现";
                webVC.isFromWithdraw = YES;
                UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:webVC];
                [weakself presentViewController:naviVC animated:YES completion:^{
                    
                }];
            });
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)popPreVC {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showCardDetailAction:(id)sender {
    
    MNDBankCardViewController *bankcardVC = [UIStoryboard viewControllerWithIdentifier:[MNDBankCardViewController description]];
    bankcardVC.bankModel = self.bankModel;
    bankcardVC.hideUnbindButton = YES;
    [self.navigationController pushViewController:bankcardVC animated:YES];
}

- (IBAction)bindCardAction:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
    
    MNDBindBankcardViewController *bindcardVC = [storyboard instantiateViewControllerWithIdentifier:[MNDBindBankcardViewController description]];
    bindcardVC.bankModel = self.bankModel;
    
    [self.navigationController pushViewController:bindcardVC animated:YES];
}

- (void)loadWithdrawParam {
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_GET_WITHDRAW_PARAM parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.withdrawParam = [MNDWithdrawParamModel mj_objectWithKeyValues:responseModel.data];
            [weakself configWithdrawParam];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configWithdrawParam {
    
    NSNumber *counterFee = [NSNumber numberWithString:self.withdrawParam.counterFee];
    self.handlingChargeDetailLabel.text = [NSString stringWithFormat:@"(充值未出借的部分收取%.0lf‰手续费, 最低%@元)", counterFee.doubleValue * 1000, self.withdrawParam.lessMoney];
    [self.withdrawTextField setPlaceholder:[NSString stringWithFormat:@"可免费提现%@元，单笔最低100元", self.withdrawParam.canFreeMoney]];
    
    __block UITextField *inputTextField = self.withdrawTextField;
    WeakSelf(self);
    [self.withdrawTextField.rac_textSignal subscribeNext:^(NSString *inputText) {
        if ([inputText containsString:@"."]) {
            NSRange range = [inputText rangeOfString:@"."];
            //首位并不能输入小数点
            if (range.location <= 0) {
                inputTextField.text = @"";
                return;
            }
            //控制只能输入小数点后两位
            
            if (inputText.length > 0 && range.location > 0 && (inputText.length - (range.location + 1)) > 2) {
                inputTextField.text = [inputText substringToIndex:inputText.length - 1];
                inputText = inputTextField.text;
            }
            
            //控制只能输入一个小数点
            NSArray *arr = [inputText componentsSeparatedByString:@"."];
            if (arr.count > 2) {
                inputTextField.text = [inputText substringToIndex:inputText.length - 1];
                inputText = inputTextField.text;
            }
        }
        
        //限制输入的数字必须为纯数字和小数点
        if (![weakself validateNumber:inputText]) {
            if (inputText.length > 1) {
                inputTextField.text = [inputText substringToIndex:inputText.length - 1];
            } else {
                inputTextField.text = @"";
                return;
            }
        }
        weakself.arrivalAmountLabel.textColor = kColorBlack;
        [weakself.handlingChargeLabel setHidden:NO];
        [weakself.handlingChargeDetailLabel setHidden:NO];
        weakself.withdrawTextField.font = [UIFont systemFontOfSize:25.0];
        
        if (inputText.length <= 0) {
            weakself.withdrawTextField.font = [UIFont systemFontOfSize:14.0];
            weakself.arrivalAmountLabel.text = @"应付金额：￥0.00";
            weakself.handlingChargeLabel.text = @"手续费：￥0.00";
//            [weakself.withdrawTextField setPlaceholder:[NSString stringWithFormat:@"可免费提现%@元，单笔最低100元", self.withdrawParam.canFreeMoney]];
            return;
        }
        
        NSNumber *avalible = [NSNumber numberWithString:weakself.withdrawParam.amountAvailable];

        //提现数额大于余额时做的处理
        if (inputText.doubleValue > avalible.doubleValue) {
            weakself.arrivalAmountLabel.text = @"金额已超过可提现余额";
            weakself.arrivalAmountLabel.textColor = kColorOrange;
            [weakself.handlingChargeLabel setHidden:YES];
            [weakself.handlingChargeDetailLabel setHidden:YES];
            
            return;
        }
        NSNumber *canFree = [NSNumber numberWithString:weakself.withdrawParam.canFreeMoney];
        NSNumber *lessMoney = [NSNumber numberWithString:weakself.withdrawParam.lessMoney];
        if (inputText.doubleValue <= canFree.doubleValue) {
            weakself.arrivalAmountLabel.text = [NSString stringWithFormat:@"应付金额：￥%.02lf", inputText.doubleValue];
            weakself.handlingChargeLabel.text = @"手续费：￥0.00";
            
            return;
        }
        
        NSDecimalNumber *inputNUmber = [NSDecimalNumber decimalNumberWithString:inputText];
        NSDecimalNumber *canFreeNumber = [NSDecimalNumber decimalNumberWithString:weakself.withdrawParam.canFreeMoney];
        NSDecimalNumber *counterFeeNumber = [NSDecimalNumber decimalNumberWithString:weakself.withdrawParam.counterFee];
        NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
            
        NSDecimalNumber *feeMoneyNUmber = [inputNUmber decimalNumberBySubtracting:canFreeNumber withBehavior:handler];
        NSDecimalNumber *feeNUmber = [feeMoneyNUmber decimalNumberByMultiplyingBy:counterFeeNumber withBehavior:handler];
        //如果提现手续费小于最低手续费按最低手续费收取
        if ([feeNUmber doubleValue] < lessMoney.doubleValue) {
            double paymoney = inputText.doubleValue + [lessMoney doubleValue];
            //应付金额大于可提现余额时直接调用全部提现
            if (paymoney >= avalible.doubleValue) {
                
                [weakself withdrawAllMoneyAction:nil];
//                weakself.arrivalAmountLabel.text = @"应付金额已超过可提现余额";
//                weakself.arrivalAmountLabel.textColor = kColorOrange;
//                [weakself.handlingChargeLabel setHidden:YES];
//                [weakself.handlingChargeDetailLabel setHidden:YES];
                return;
            }
            weakself.handlingChargeLabel.text = [NSString stringWithFormat:@"手续费：￥%.02lf", lessMoney.doubleValue];
            weakself.arrivalAmountLabel.text = [NSString stringWithFormat:@"应付金额：￥%.02lf", inputText.doubleValue + [lessMoney doubleValue]];
        } else {
            double paymoney = inputText.doubleValue + [feeNUmber doubleValue];
            //应付金额大于可提现余额时直接调用全部提现
            if (paymoney >= avalible.doubleValue) {
                [weakself withdrawAllMoneyAction:nil];
//                weakself.arrivalAmountLabel.text = @"应付金额已超过可提现余额";
//                weakself.arrivalAmountLabel.textColor = kColorOrange;
//                [weakself.handlingChargeLabel setHidden:YES];
//                [weakself.handlingChargeDetailLabel setHidden:YES];
                return;
            }
            weakself.handlingChargeLabel.text = [NSString stringWithFormat:@"手续费：￥%@", feeNUmber];
            weakself.arrivalAmountLabel.text = [NSString stringWithFormat:@"应付金额：￥%.02lf", inputText.doubleValue + [feeNUmber doubleValue]];
        }
    }];
}

/**
 检测输入的数字是否纯数字和小数点

 @param number 输入的数字
 @return YES=有效 NO=无效
 */
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)loadBankInfo {
    
    WeakSelf(self);
    
    [NetworkProgressHUD showHud];
    [APIManager sendRequestWithPath:API_GET_BANK_ACCOUNT parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            [NetworkProgressHUD hideHud];
            weakself.bankModel = [MNDBankModel mj_objectWithKeyValues:responseModel.data];
            [weakself configBankInfo];
            
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configBankInfo {
    if (self.bankModel.jxBankaccount.userAmountIssetcardno.integerValue == -1) {
        self.bankLogoImageView.image = [UIImage imageNamed:@"bank_logo_placeholder"];
        self.bankLabel.text = @"您还未绑定银行卡";
        self.bankcardLabel.text = @"先绑卡再提现哦";
//        [self.cardDetailBtn setEnabled:NO];
        [self.bindCardBtn setEnabled:YES];
        [self.bindCardBtn setTitle:@"绑卡" forState:UIControlStateNormal];
        self.bindCardBtn.titleLabel.textColor = kColorOrange;
    } else {
        
        NSString *logoUrl = self.bankModel.jxBankaccount.bank.banklogo;
        [self.bankLogoImageView sd_setImageWithURL: [NSURL URLWithString:logoUrl] placeholderImage:[UIImage imageNamed:@"bank_logo_placeholder"]];
        
        self.bankLabel.text = self.bankModel.jxBankaccount.bank.bank;
        self.bankcardLabel.text = [NSString stringWithFormat:@"尾号%@", self.bankModel.jxBankaccount.lastNumber];
        
//        [self.cardDetailBtn setEnabled:NO];
        [self.bindCardBtn setEnabled:NO];
        [self.bindCardBtn setTitle:@"提现至此卡" forState:UIControlStateNormal];
        self.bindCardBtn.titleLabel.textColor = kColorGray;
        
    }
    self.userBalanceLabel.text = [NSString stringWithFormat:@"可提现余额：￥%@", self.bankModel.userAmount.userAmountAvailable];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
